package com.suncnpap.library.controller;

import com.suncnpap.library.model.BookLoss;
import com.suncnpap.library.model.BorrowBook;
import com.suncnpap.library.model.BorrowBookInfo;
import com.suncnpap.library.model.BorrowBookRecord;
import com.suncnpap.library.model.CollectionChange;
import com.suncnpap.library.model.IntegralSet;
import com.suncnpap.library.model.Library;
import com.suncnpap.library.model.ReturnBook;
import com.suncnpap.library.service.BookLossService;
import com.suncnpap.library.service.BorrowBookRecordService;
import com.suncnpap.library.service.BorrowBookService;
import com.suncnpap.library.service.IntegralSetService;
import com.suncnpap.library.service.LibraryService;
import com.suncnpap.library.service.ReturnBookService;
import com.suncnpap.library.service.BorrowBookService;
import com.suncnpap.reader.model.Reader;
import com.suncnpap.reader.model.ReaderType;
import com.suncnpap.reader.service.ReaderService;
import com.suncnpap.reader.service.ReaderTypeService;
import com.suncnpap.statistics.annotation.LogType;
import com.suncnpap.statistics.annotation.SysLog;
import com.suncnpap.system.model.Config;
import com.suncnpap.system.model.School;
import com.suncnpap.system.service.ConfigService;
import com.suncnpap.system.service.HolidayService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.util.beanutil.BeanUtil;
import com.app.util.common.Constants;
import com.app.util.common.DateUtil;
import com.app.util.common.EasyuiGrid;
import com.app.util.common.HandlerResult;
import com.app.util.common.ObjUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.common.UuidUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.base.common.ParamModel;
import com.suncnpap.base.controller.BaseController;
import com.suncnpap.datamanage.common.ExportExcelUtils;

/** 
 * 说明：期刊Controller
 */
@Controller
@RequestMapping(value="/library/circulate")
public class LibraryCirculateController extends BaseController {
	
	@Autowired
	LibraryService libraryService;
	
	@Autowired
	ReaderService readerService;
	
	@Autowired
	BorrowBookService borrowBookService;
	
	@Autowired
	BorrowBookRecordService borrowBookRecordService;
	
	@Autowired
	ReturnBookService returnBookService;
	
	@Autowired
	ReaderTypeService readerTypeService;
	
	@Autowired
	BookLossService bookLossService;
	
	@Autowired
	IntegralSetService integralSetService;
	
	@Autowired
	HolidayService holidayService;
	
	@Autowired
	ConfigService configService;
	
	@RequestMapping(value="/getReader")
	public void getReader(@RequestBody ParamModel paramModel,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				
				String strSchoolId = String.valueOf(result.get("strSchoolId"));
				
				Reader reader = new Reader();
				String keyName = paramModel.getKeyName();
				String keywords = paramModel.getKeywords();
				if(keyName!=null && !keyName.equals("")){
					if(keyName.equals("卡号")){
						reader = readerService.findByCardNumber(keywords, strSchoolId);
					}else if(keyName.equals("学号")){
						reader = readerService.findByStudentNumber(keywords, strSchoolId);
					}else if(keyName.equals("姓名")){
						reader = readerService.findByName(keywords, strSchoolId);
					}
				}else{
					reader = readerService.findByCardNumber(paramModel.getStrCardNumber(), strSchoolId);
				}
				
				
				if(reader!=null){
					String strCardNumber = reader.getStrCardNumber();
					ReaderType readerType = readerTypeService.findById(reader.getStrReaderTypeId());
					
					Page page = new Page();
					page.addQueryAnd("br.strReaderCardNumber", strCardNumber);
					page.put("over", "1");
					page.setUsePage(false);
//					page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
					List<BorrowBookInfo> borrowBookList = borrowBookService.listInfo(page).getDataList();
					int intBorrow = borrowBookList.size();
					int intNoBorrow = readerType.getIntNumOfBook()-intBorrow;
					
					result.put("borrowBookList", borrowBookList);
					result.put("intBorrow", intBorrow);
					result.put("intNoBorrow", intNoBorrow);
					
					reader.setStrSex(reader.getStrSex().equals("1")?"男":"女");
					result.put("reader", reader);
					
					Config config = configService.findBySchoolId(strSchoolId);
					result.put("fBookOverdueFineAmount", config.getfBookOverdueFineAmount());
					result.put("fBookLostFineMultiple", config.getfBookLostFineMultiple()==null?1:config.getfBookLostFineMultiple());
				}else{
					result.setCode(1);
					result.setMessage("不存在的读者卡号");
				}
				
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}

	/**
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/list" )
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		
		if (result.getCode()==0) {

			Page page = this.setPage();
			
			page.put("user", "true");
			page.put("isUnit", "true");
			page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
			page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
			
			page.removeQueryAnd("strSchoolId");
			page.addQueryAnd("br.strSchoolId", GlobaUser.getStrSchoolId(request.getHeader("token")));
			
			
			String strUnitId = this.getParameter("strUnitId","");
			if(!strUnitId.equals("")){
				page.put("strUnitId", strUnitId);
				page.addQueryAnd("r.strUnitId", strUnitId);
			}
			
			String dtStartCreatDate = this.getParameter("dtStartCreatDate", "");
			if(!dtStartCreatDate.equals("")){
				page.addQueryAnd("br.dtCreatDate", QueryType.markGTEQ, dtStartCreatDate);
			}
			
			String dtEndCreatDate = this.getParameter("dtEndCreatDate", "");
			if(!dtEndCreatDate.equals("")){
				page.addQueryAnd("br.dtCreatDate", QueryType.markLTEQ, dtEndCreatDate);
			}
			
			String keyName = this.getParameter("keyName", "");
			String keywords = this.getParameter("keywords", "");
			if(!keyName.equals("")){
				if(keyName.equals("strBookBarcode")){
					page.addQueryAnd("br.strBookBarcode", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strPositiveTitle")){
					page.addQueryAnd("l.strPositiveTitle", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strName")){
					page.addQueryAnd("r.strName", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strCardNumber")){
					page.addQueryAnd("br.strReaderCardNumber", QueryType.markLIKE, keywords);
				}
			}
			
			String strGradeId = this.getParameter("strGradeId", "");
			if(!strGradeId.equals("")){
				page.addQueryAnd("r.strGradeId", strGradeId);
			}
			
			String strClassId = this.getParameter("strClassId", "");
			if(!strClassId.equals("")){
				page.addQueryAnd("r.strClassId", strClassId);
			}
			
			String strType = this.getParameter("strType","");
			if(!strType.equals("")){
				if(strType.equals("未还")){
					page = borrowBookService.listInfo(page);
				}else if(strType.equals("已还")){
//					page.addQueryAnd("br.dtReturnDate", QueryType.MarkISNOTNULL,"");
					page.addQueryAnd("br.isReturn",1);
					page = borrowBookRecordService.listInfo(page);
				}else if(strType.equals("损毁丢失")){
					page = bookLossService.listInfo(page);
				}
			}else{
				page = borrowBookRecordService.listInfo(page);
			}
			
			String isExp = this.getParameter("isExp", "");
			if(isExp.equals("1")){
				List<BorrowBookInfo> list = page.getDataList();
				String header = "";
				String tableStr = "";
				if(strType.equals("损毁丢失")){
					header = "图书条码,正题名,级,班,所属书屋,读者卡号,姓名,部门,赔偿金额,操作时间,丢失、损毁,操作员";
					tableStr = "strBookBarcode,strPositiveTitle,strGrade,strClass,strCollectionLocation,strReaderCardNumber,strReaderName,strUnitName,strAmountPaid,dtCreatDate,strType,strCreatName";
				}else{
					header = "卡号,姓名,级,班,部门,所借图书,图书条码,借阅时间,应还时间,操作员";
					tableStr = "strReaderCardNumber,strReaderName,strGrade,strClass,strUnitName,strPositiveTitle,strBookBarcode,dtBorrowDate,dtReturnDate,strCreatName";
				}
				
				ExportExcelUtils util = new ExportExcelUtils();
				String path = "upload/exp/";
				String fileName = UuidUtil.get32UUID()+".xls";
				util.exportExcel("图书流通", ObjUtil.strToList(header), ObjUtil.strToList(tableStr),list, path, fileName);
				
				result.put("path", path);
				result.put("fileName", fileName);
			}else{
				result = this.returnPage(result, page);
			}

		}
		
		ResponseUtil.writeJson(result, response);

	}
	
	/**
	 * 借阅处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/borrowBook",method=RequestMethod.POST)
	@SysLog(type=LogType.BOOKBORROW)
	public void borrowBook(@RequestBody BorrowBook obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = GlobaUser.getStrSchoolId(request.getHeader("token"));
				Library library = libraryService.findByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
				BookLoss bookLoss = bookLossService.findByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
				if(library!=null){
					if(bookLoss==null){
						BorrowBook borrowBook = borrowBookService.findByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
						
						if(borrowBook==null){
							Reader reader = readerService.findByCardNumber(obj.getStrReaderCardNumber(), strSchoolId);
							
							Page page = new Page();
							page.addQueryAnd("strSchoolId", strSchoolId);
							page.addQueryAnd("strStartTime", QueryType.markGTEQ, DateUtil.get(new Date(), "yyyy-mm-dd"));
							page.addQueryAnd("strEndTime", QueryType.markLTEQ, DateUtil.get(new Date(), "yyyy-mm-dd"));
							int count = holidayService.findCount(page);
							
							if(count>0){
								result.setMessage("假期内不能借书");
							}else{
	//							ReaderType readerType = readerTypeService.findById(reader.getStrReaderTypeId());
								Config config = configService.findBySchoolId(strSchoolId);
								
								Calendar cal = Calendar.getInstance();
								super.init(obj);
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								obj.setDtBorrowDate(sdf.parse(sdf.format(cal.getTime())));
								int intBorrowingDays = 5;
								if(config.getIntDefaultBorrowDays()!=null){
									intBorrowingDays = config.getIntDefaultBorrowDays();
								}
								cal.add(Calendar.DATE, intBorrowingDays);
								obj.setDtReturnDate(cal.getTime());
								borrowBookService.add(obj);
								
								BorrowBookRecord borrowBookRecord = new BorrowBookRecord();
								BeanUtil.copyBean(obj, borrowBookRecord);
	//							borrowBookRecord.setDtReturnDate(null);
								borrowBookRecord.setIsReturn(0);
								borrowBookRecord.setIntRenewCount(0);
								borrowBookRecordService.add(borrowBookRecord);
								
								libraryService.updateBorrowById(obj.getStrBookBarcode(), result.get("strSchoolId")+"");
								
								IntegralSet integralSet = integralSetService.findBySchoolId(reader.getStrSchoolId());
								if(integralSet!=null){
//									if(integralSet.getIntTimeBar()>=num){
										reader.setIntIntegral(reader.getIntIntegral()+integralSet.getIntIntegral());
										readerService.update(reader);
//									}
								}
							}
						}else{
							result.setCode(1);
							result.setMessage("该图书已经被借出");
						}
					}else{
						result.setCode(1);
						result.setMessage("该图书已经丢失/损毁");
					}
				}else{
					result.setCode(1);
					result.setMessage("不存在的图书条码");
				}
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 归还处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/returnBook",method=RequestMethod.POST)
	@SysLog(type=LogType.RETURNBOOK)
	public void returnBook(@RequestBody BorrowBook obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = String.valueOf(result.get("strSchoolId"));
				
				BorrowBookRecord borrowBookRecord = borrowBookRecordService.findByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
				
				if(borrowBookRecord!=null){
//					Config config = configService.findBySchoolId(GlobaUser.getStrSchoolId("token"));
//					if(config!=null && config.getIntIsAppoint()!=null && config.getIntIsAppoint()==1){
//						Library library = libraryService.findByBookBarcode(obj.getStrBookBarcode());
//						if(!config.getStrCollectionLocationId().equals(library.getStrCollectionLocation())){
//							
//						}
//					}
					
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					borrowBookRecord.setDtReturnDate(sdf.parse(sdf.format(new Date())));
					borrowBookRecord.setIsReturn(1);
					borrowBookRecordService.update(borrowBookRecord);
					
					ReturnBook returnTemp = new ReturnBook();
					BeanUtil.copyBean(borrowBookRecord, returnTemp);
					init(returnTemp);
					returnBookService.add(returnTemp);
					
					Page page = new Page();
					page.addQueryAnd("br.strReaderCardNumber", borrowBookRecord.getStrReaderCardNumber());
					page.addQueryAnd("br.strBookBarcode", borrowBookRecord.getStrBookBarcode());
					page.setUsePage(false);
					page.put("over", "true");
//					page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
					
					List<BorrowBookInfo> borrowBookRecordList = borrowBookService.listInfo(page).getDataList();
					
					borrowBookService.deleteByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
					
					libraryService.updateReturnById(obj.getStrBookBarcode(), result.get("strSchoolId")+"");
					
					Reader reader = readerService.findByCardNumber(borrowBookRecord.getStrReaderCardNumber(), strSchoolId);
					int num = (int) ((borrowBookRecord.getDtReturnDate().getTime()-borrowBookRecord.getDtBorrowDate().getTime())/(24*60*60*1000));
					IntegralSet integralSet = integralSetService.findBySchoolId(reader.getStrSchoolId());
					if(integralSet!=null){
						int minday = integralSet.getIntMinDay();
						int maxday = integralSet.getIntMaxDay();
						if(minday<=num && maxday>=num ){
							reader.setIntIntegral(reader.getIntIntegral()+integralSet.getIntIntegral());
							readerService.update(reader);
						}
					}
					
					page = new Page();
					page.put("over", "true");
					page.addQueryAnd("br.strReaderCardNumber", reader.getStrCardNumber());
					page.setUsePage(false);
//					page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
					
					List<BorrowBookInfo> borrowBookList = borrowBookService.listInfo(page).getDataList();
					
					result.put("borrowBookList", borrowBookList);
					result.put("borrowBookRecord", borrowBookRecordList);
					result.put("reader", reader);
					
					Config config = configService.findBySchoolId(strSchoolId);
					result.put("fBookOverdueFineAmount", config.getfBookOverdueFineAmount());
					
					
				}else{
					result.setCode(1);
					result.setMessage("该图书没有被借阅");
				}
				
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 续借处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/continueBorrowBook",method=RequestMethod.POST)
	public void continueBorrowBook(@RequestBody BorrowBook obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = GlobaUser.getStrSchoolId(request.getHeader("token"));
				//图书借阅
				obj = borrowBookService.findByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
				if(obj != null){
					Config config = configService.findBySchoolId(strSchoolId);
					BorrowBookRecord borrowBookRecord = borrowBookRecordService.findByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
					
					//系统设置的最大续借次数
					int intMaxRenewCount = config.getIntMaxRenewCount();
					//当前借阅续借次数
					int intRenewCount = borrowBookRecord.getIntRenewCount();
					
					if(intMaxRenewCount>intRenewCount){
						Calendar cal = Calendar.getInstance();
						int intBorrowingDays = 5;
						if(config.getIntDefaultBorrowDays()!=null){
							intBorrowingDays = config.getIntDefaultBorrowDays();
						}
						cal.add(Calendar.DATE, intBorrowingDays);
						obj.setDtReturnDate(cal.getTime());
						borrowBookService.update(obj);
						
						borrowBookRecord.setDtReturnDate(obj.getDtReturnDate());
						borrowBookRecord.setIntRenewCount(borrowBookRecord.getIntRenewCount()+1);
						borrowBookRecordService.update(borrowBookRecord);
					}else{
						result.setCode(1);
						result.setMessage("已超过最大续借次数");
					}
					
				}else{
					result.setCode(1);
					result.setMessage("不存在的图书条码或该图书没有被借出");
				}
				
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
}
